﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Micrhard.FMCG.Server.Interface;
using Micrhard.FMCG.Server.DataAccess;
using Microhard.Core.DBUtility;
using Micrhard.FMCG.Server.Msg;
using Microhard.Core;
using Micrhard.FMCG.Server.DTO;
using Micrhard.FMCG.Server.Models;
using System.Data.Objects;
using Microhard.Core.Algorithm;

namespace Micrhard.FMCG.Server.Impl
{
    public class DailyImpl : IDaily
    {
        public bool IsDuplicate(Models.DailyModel model)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var now = DateTime.Now.Date;
            var end = now.AddDays(1).Date;
            var cnt = db.Dailies.Where(d => d.Employee.UserName == model.CurrentLoginUserName
                && (d.CreateTime >= now && d.CreateTime <= end)).Count();
            return cnt > 0 ? true : false;
        }

        public Microhard.Core.DBUtility.ExecutedResult Add(Models.DailyModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var op = model.ToEntity();
            op.CreateTime = DateTime.Now;

            try
            {
                var emp = db.Employees.Single(w => w.UserName == scope.CurrentUserName);
                op.EmployeeID = emp.EmployeeID;
                db.Dailies.AddObject(op);

                if (model.TommrowPlanProtalSubKA != null)
                {
                    foreach (var m in model.TommrowPlanProtalSubKA)
                    {
                        db.ProtalSubKAPlans.AddObject(new ProtalSubKAPlan
                        {
                            CreateTime = DateTime.Now,
                            ProtalSubKAID = Guid.NewGuid(),
                            ProtalTime = DateTime.Now,
                            SubKAID = m.SubKAID,
                            DailyWorkID = op.DailyID
                        });
                    }
                }
                db.SaveChanges();
                if (!string.IsNullOrEmpty(model.WeixinName) && !string.IsNullOrEmpty(model.WeixinToken))
                {
                    model.CurrentCondition = "mobileAdd";
                }
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, DailyMsg.AddFailed);
                Log.Error("IDaily.Add", ex);
            }
            return rtn;
        }

        public Microhard.Core.DBUtility.ExecutedResult Update(Models.DailyModel model)
        {
            ExecutedResult result = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var entity = db.Dailies.SingleOrDefault(l => l.DailyID == model.DailyID);
            if (entity != null)
            {
                entity.TodayFinished = model.TodayFinished;
                entity.Question = model.Question;
                entity.Comment = model.Comment;
                entity.TodayPlan = model.TodayPlan;
                entity.Help = model.Help;
                entity.TommrowPlan = model.TommrowPlan;

                //获取到需要变更的巡店
                var exist = entity.ProtalSubKAPlans.Select(t => t.ToModel()).ToList();
                var newInput = model.TommrowPlanProtalSubKA;
                List<ProtalSubKAPlanModel> toAdd, todel;
                AlgCompare.DataCompareForCreateAndDelete<ProtalSubKAPlanModel>(exist, newInput, new ProtalSubKAPlanComparer(), out todel, out toAdd);
                if (todel != null && todel.Count > 0)
                {
                    todel.ForEach(d =>
                    {
                        var delEntity = db.ProtalSubKAPlans.SingleOrDefault(del => del.ProtalSubKAID == d.ProtalSubKAID);
                        db.ProtalSubKAPlans.DeleteObject(delEntity);
                    });
                }
                if (toAdd != null && toAdd.Count > 0)
                {
                    toAdd.ForEach(a =>
                    {
                        db.ProtalSubKAPlans.AddObject(new ProtalSubKAPlan
                        {
                            ProtalSubKAID = Guid.NewGuid(),
                            DailyWorkID = entity.DailyID,
                            SubKAID = a.SubKAID,
                            ProtalTime = entity.CreateTime.Value.Date,
                            CreateTime = DateTime.Now
                        });
                    });
                }
            }
            try
            {
                db.SaveChanges();
                if (!string.IsNullOrEmpty(model.WeixinName) && !string.IsNullOrEmpty(model.WeixinToken))
                {
                    model.CurrentCondition = "mobileAdd";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.UpdateFailed, DailyMsg.UpdateFailed);
                Log.Error("IDaily.Update", ex);
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(Models.DailyModel model)
        {
            throw new NotImplementedException();
        }

        public Models.DailyModel GetModelByID(Guid id)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var model = db.Dailies.SingleOrDefault(c => c.DailyID == id);
            if (model != null)
            {
                var result = model.ToModel();
                result.TommrowPlanProtalSubKA = model.ProtalSubKAPlans.Select(t => t.ToModel()).ToList();
                string userName = this.scope.CurrentUserName;
                return result;
            }
            return null;
        }

        public Models.DailyModel GetModelByModel(Models.DailyModel model)
        {
            throw new NotImplementedException();
        }

        public List<Models.DailyModel> Query(Models.DailyModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var cmp = db.Employees.SingleOrDefault(e => e.UserName == this.scope.CurrentUserName);
            IEnumerable<Daily> entities = from b in db.Dailies
                                          where this.scope.PKID.Contains(b.DailyID)
                                          && b.Employee.CompanyID == cmp.CompanyID
                                          select b;
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<DailyModel>();
        }

        public List<Models.DailyModel> Query(Models.DailyModel Model)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }

        public bool IsApproved(Guid DailyID)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var cnt = db.DailyComments.Count(d => d.DailyID == DailyID);
            return cnt > 0 ? true : false;
        }
    }
}
